/*
Copyright (c) 2023 China Mobile Information Technology Co., Ltd
OpenGauss Operator is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
         http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
*/

package service

import (
	"fmt"
	"k8s.io/klog/v2"
	gsv1 "openGauss-operator/api/v1"
	customClient "openGauss-operator/internal/client"
	"openGauss-operator/internal/util"
)

type SwitchoverInterface interface {
	Switchover(gs *gsv1.OpenGaussCluster, targetMasterPod string) error
}

type Switchover struct {
	K8sClient customClient.K8sClient
}

var _ SwitchoverInterface = &Switchover{}

func NewSwitchover(client customClient.K8sClient) SwitchoverInterface {
	return &Switchover{K8sClient: client}
}

func (r *Switchover) Switchover(gs *gsv1.OpenGaussCluster, targetMasterPod string) error {
	switchover := gs.Spec.Switchover
	status := switchover.Status

	if status != util.SOBegin {
		return nil
	}

	if targetMasterPod == "" {
		if switchover.TargetMasterPod == "" {
			klog.Error("TargetMasterPod is nil.")
			return nil
		}
		targetMasterPod = switchover.TargetMasterPod
	}

	sourceName, err := r.K8sClient.GetPrimaryPodName(gs)

	klog.Info(fmt.Sprintf("Primary pod name: %s", sourceName))
	modifyGs := gs.DeepCopy()
	if err == nil {
		if sourceName == targetMasterPod {
			status = util.SOComplete
			modifyGs.Spec.Switchover.Status = status
			if err := r.K8sClient.UpdateOpenGaussClusterObject(modifyGs, gs); err != nil {
				klog.Error(util.ReturnError("Switchover update gs error:", err))
			}
			return nil
		}
		_, err = r.K8sClient.ExecCommand(gs.Namespace, util.Command(util.CommandSwitchover), targetMasterPod)
		if err == nil {
			status = util.SOComplete
		} else {
			status = util.SOFailed
		}
	} else {
		status = util.SOFailed
	}
	modifyGs.Spec.Switchover.Status = status
	if err := r.K8sClient.UpdateOpenGaussClusterObject(modifyGs, gs); err != nil {
		klog.Error(util.ReturnError("Switchover update gs error:", err))
	}
	return err
}
